package com.example.mybaseapp.util

import androidx.annotation.NonNull
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.example.mybaseapp.vt.VTAdapter
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator

class ViewPagerTabLayoutUtil {
    /**
     * 在使用之前最好设置好ViewPager2的adapter
     */
    fun contactViewPagerWithTabLayout(viewPager2: ViewPager2,tabLayout: TabLayout, listener: ViewPagerTabLayoutListener){
        tabLayout.apply {
            addOnTabSelectedListener(object :TabLayout.OnTabSelectedListener{
                override fun onTabSelected(tab: TabLayout.Tab?) {
                    listener.onTabSelected(tab!!)
                }

                override fun onTabUnselected(tab: TabLayout.Tab?) {
                    listener.onTabUnselected(tab!!)
                }

                override fun onTabReselected(tab: TabLayout.Tab?) {
                    listener.onTabReselected(tab!!)
                }

            })
        }
        viewPager2.apply {
//            当前选中的tab
            currentItem = 0
            //禁用预加载
            setOffscreenPageLimit(ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT)
        }

        TabLayoutMediator(tabLayout, viewPager2
        ) { tab, position ->
            listener.onConfigureTab(tab, position)
        }.attach()
    }

    interface ViewPagerTabLayoutListener{
        /**初次配置所有的子tab*/
        fun onConfigureTab(tab: TabLayout.Tab, position:Int)
        fun onTabSelected(tab: TabLayout.Tab)
        fun onTabUnselected(tab: TabLayout.Tab)
        fun onTabReselected(tab: TabLayout.Tab)

    }

    class VTAdapter(fragment: AppCompatActivity, private val fragments: ArrayList<Fragment>) :
        FragmentStateAdapter(fragment) {
        override fun getItemCount(): Int {
            return fragments.size
        }

        override fun createFragment(position: Int): Fragment {
            return fragments[position]
        }

    }
}